import CryptoJS from 'crypto-js'

/**
 * AES 加密
 * @param word: 需要加密的文本
 * KEY: // 需要前后端保持一致
 * mode: ECB // 需要前后端保持一致
 * pad: Pkcs7 //前端 Pkcs7 对应 后端 Pkcs5
 */
export class AES {
  KEY = CryptoJS.enc.Utf8.parse('3.1415926')
  constructor(secretKey: string) {
    const difference = 16- secretKey.length % 16
    const differenceCode = [
      'd',
      '7',
      'b',
      '8',
      '5',
      'f',
      '6',
      'e',
      '2',
      '1',
      '4',
      'a',
      'b',
      'c',
      'd',
      'e',
    ]
    for (let i = 0; i < difference; i++) {
      secretKey += differenceCode[i]
    }
    this.KEY = CryptoJS.enc.Utf8.parse(secretKey)
  }
  encrypt = (plaintext: string) => {
    let ciphertext = CryptoJS.AES.encrypt(plaintext, this.KEY, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }).toString()
    return ciphertext
  }

  /**
   * AES 解密
   * @param jsonStr
   */
  decrypt = (jsonStr: string) => {
    let plaintext = CryptoJS.AES.decrypt(jsonStr, this.KEY, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }).toString(CryptoJS.enc.Utf8)

    return plaintext
  }
}
